package com.ljh.nio.c3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @author: Themberfue
 * @date: 2025/5/26 19:44
 * @description:
 */
public class ServerWrite2 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);

        ssc.bind(new InetSocketAddress(8080));

        while (true) {
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buffer = StandardCharsets.UTF_8.encode("a".repeat(5000000));

                    int write = sc.write(buffer);
                    System.out.println(write);

                    if (buffer.hasRemaining()) { // ! 一次写入还没写完
                        // ? 交给 selector 进行管理（即关注读又关注写）
                        SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_READ + SelectionKey.OP_WRITE);
//                        sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                        // ? 将 buffer 附件给 selector
                        selectionKey.attach(buffer);
                    }
                } else if (key.isWritable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();

                    int write = sc.write(buffer);
                    System.out.println(write);

                    if (!buffer.hasRemaining()) { // ! 此时 buffer 没有剩余数据了
                        // ? 将 buffer 从附件中清空，节省空间
                        key.attach(null);
                        // ! 不需关注可写事件
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }
            }
        }
    }
}
